﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Security.Permissions;
using System.Reflection;
using System.Windows;

namespace AutomationLib
{
    public class AutoTestSTAHelper
    {
        private Thread CreateSTAThread(Action action)
        {
            Thread thread = new Thread(() => action());
            thread.SetApartmentState(ApartmentState.STA);
            return thread;
        }

        Exception lastException;


        public void RunTest(Action testLogic)
        {
            lastException = null;

            Action actionWrapper = () =>
            {
                try
                {
                    testLogic();
                }
                catch (Exception ex)
                {
                    lastException = ex;
                }
            };

            
            Thread thread = CreateSTAThread(actionWrapper);
            thread.Start();
            thread.Join();

            if (lastException != null)
                ThrowExceptionPreservingStack(lastException);
           
        }

        [ReflectionPermission(SecurityAction.Demand)]
        private static void ThrowExceptionPreservingStack(Exception exception)
        {
            FieldInfo remoteStackTraceString = typeof(Exception).GetField(
              "_remoteStackTraceString",
              BindingFlags.Instance | BindingFlags.NonPublic);
            remoteStackTraceString.SetValue(exception, exception.StackTrace + Environment.NewLine);
            throw exception;
        }
    }
}
